package com.hp.easyBuy.controller;

import com.hp.easyBuy.contants.RedixKey;
import com.hp.easyBuy.entity.DTO.TCartDto;
import com.hp.easyBuy.entity.TCart;
import com.hp.easyBuy.entity.TGoods;
import com.hp.easyBuy.entity.TOrder;
import com.hp.easyBuy.entity.TUser;
import com.hp.easyBuy.service.CartService;
import com.hp.easyBuy.service.OrderService;
import com.hp.easyBuy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @RequestMapping("/getCartList")
    public R getCartList(@RequestParam Long userid){
        List<TCartDto> cartList = cartService.getCartList(userid);
        return R.success(cartList);
    }

    //删除购物车订单
    @RequestMapping("/del")
    public R del(@RequestParam Long cartid){
        cartService.removeById(cartid);
        return R.success();
    }

    //增加减少订单数量
    @RequestMapping("/updateCartNum")
    public R updateCartNum(@RequestParam Long cartid, @RequestParam Long num){
        boolean result = cartService.updateCartNum(cartid, num);
        if (result){
            return R.success();
        }else {
            return R.error();
        }
    }

     //添加商品进入购物车
    @RequestMapping("addCart")
    public R addCart(Integer goodsid, HttpServletRequest req){
        //从req里面获取对应的token，然后从redis里面获取对应的user信息
        String token = req.getHeader("token");
        //从redis获取对应的用户信息
        TUser user = (TUser)redisTemplate.opsForValue().get(RedixKey.LOGIN_USER+token);
        boolean result = cartService.addCart(goodsid, user.getUserid());
        if(result){
            return R.success();
        }else{
            return R.error();
        }
    }

    //结算功能
    @RequestMapping("settle")
    public R settle(Long addressid,HttpServletRequest req){
        //从数据头里面取出token
        String token = req.getHeader("token");
        //从redis里面取出token对应的用户信息
        TUser user = (TUser) redisTemplate.opsForValue().get(RedixKey.LOGIN_USER + token);
        boolean result = orderService.settle(user.getUserid(), addressid);
        //根据结果选择返回数据
        if(result){
            return R.success();
        }else{
            return R.error();
        }
    }


}
